package com.zxisl.javamail;

import com.sun.mail.iap.Argument;
import com.sun.mail.iap.ProtocolException;
import com.sun.mail.imap.protocol.IMAPProtocol;
import com.sun.mail.util.MailLogger;

import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Properties;

/**
 * Created by ade on 2016/11/9.
 */
public class IMAP2Protocol extends IMAPProtocol {

    public IMAP2Protocol(String name, String host, int port, Properties props, boolean isSSL, MailLogger logger) throws IOException, ProtocolException {
        super(name, host, port, props, isSSL, logger);
    }

    @Override
    public String writeCommand(String command, Argument args)
            throws IOException, ProtocolException {

        // assert Thread.holdsLock(this);
        // can't assert because it's called from constructor
        DataOutputStream output = (DataOutputStream) this.getOutputStream();
        byte[] CRLF = {(byte) '\r', (byte) '\n'};
        //反射获取tagCounter 还有 CRLF
        try {
            Field tagCounterField = this.getClass().getSuperclass().getSuperclass().getDeclaredField("tagCounter");
            tagCounterField.setAccessible(true);
            int tagCounter = tagCounterField.getInt(this);
            tagCounterField.set(this, tagCounter + 1);
            tagCounter++;
            if (tagCounter == 2) {
                output.writeBytes("C2 ID (\"name\" \"com.tencent.foxmail\" \"version\" \"7.2.7.174\" \"os\" \"windows\" \"os-version\" \"6.2\" \"vendor\" \"tencent limited\" \"contact\" \"foxmail@foxmail.com\")");
                //          println("C2 ID (\"name\" \"com.tencent.foxmail\" \"version\" \"7.2.7.174\" \"os\" \"windows\" \"os-version\" \"6.2\" \"vendor\" \"tencent limited\" \"contact\" \"foxmail@foxmail.com\")")
                tagCounter++;
                tagCounterField.set(this, tagCounter);
                output.write(CRLF);
                output.flush();
            }
            tagCounterField.setAccessible(false);
            String tag = "C" + Integer.toString(tagCounter, 10);
            output.writeBytes(tag + " " + command);
            //      println(tag + " " + command)

            if (args != null) {
                output.write(' ');
                args.write(this);
            }

            output.write(CRLF);
            output.flush();
            return tag;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
